#include "mencoder.h"
#include "QDir"

using namespace std;

MEncoder::MEncoder() :
    QProcess(0)
{
    state = none;
    complete = "";
    file = 0;

    inputDirecory = ".";
    outputDirectory = ".";
    outputFile = "output";
    merge = true;
    aspect = aspect43;
    startIndex = 0;


    connect(this, SIGNAL( started()), this, SLOT( started() ));
    connect(this, SIGNAL( readyReadStandardOutput() ), this, SLOT( readStandardOutput() ));
    connect(this, SIGNAL(finished(int)), this, SLOT(finished()));
}

MEncoder::~MEncoder()
{
    terminate();
}

void MEncoder :: setInputDirectory( QString directory )
{
    inputDirecory = directory;
}

void MEncoder :: setOutputDirectory( QString directory )
{
    outputDirectory = directory;
}

void MEncoder :: setOutputFilename( QString fileName )
{
    outputFile = fileName;
}

void MEncoder :: setMerge( bool merge )
{
    this->merge = merge;
}

void MEncoder :: setAspect( AspectRatio aspect )
{
    this->aspect = aspect;
}

QString MEncoder :: getAspectRatio()
{
    switch( aspect )
    {
    case aspect169:
        return "16/9";
    case aspect43:
        return "4/3";
    }
    return "4/3";
}

QString MEncoder :: getOutputFilename()
{
    if( merge )
        return outputDirectory + "/" + outputFile;
    return outputDirectory + "/" + files.at( startIndex );
}

QStringList& MEncoder :: getInputFiles()
{
    return files;
}

QString& MEncoder :: getInputDirectory()
{
    return inputDirecory;
}


void MEncoder :: start()
{
    QDir videos(inputDirecory);
    files = videos.entryList(QStringList("*"),QDir::Files);

    // mencoder
    //  -oac lavc
    //  -ovc lavc
    //  -of mpeg
    //  -mpegopts format=xsvcd
    //  -vf scale=480:576,harddup
    //  -srate 44100
    //  -af lavcresample=44100
    //  -lavcopts vcodec=mpeg2video:mbd=2:keyint=15:vrc_buf_size=917:vrc_minrate=600:vbitrate=2500:vrc_maxrate=2500:acodec=mp2:abitrate=224:aspect=$1
    //  -ofps 25
    //  -o $3
    //  $2

    QStringList argument;
    argument
    << "-oac" << "lavc"
    << "-ovc" << "lavc"
    << "-of" << "mpeg"
    << "-mpegopts" << "format=xsvcd"
    << "-vf" << "scale=480:576,harddup"
    << "-srate" << "44100"
    << "-af" << "lavcresample=44100"
    << "-lavcopts" << QString("vcodec=mpeg2video:mbd=2:keyint=15:vrc_buf_size=917:vrc_minrate=600:vbitrate=2500:vrc_maxrate=2500:acodec=mp2:abitrate=224:aspect=") + QString(getAspectRatio())
    << "-ofps" << "25"
    << "-o" << getOutputFilename();

    for( int i=startIndex; i<files.size(); ++i)
    {
        QString file = files.at(i);
        argument << videos.absolutePath() + "/" + file;

        if( !merge )
            break;
    }

    QProcess::start("mencoder", argument );
}

void MEncoder :: started()
{
}

void MEncoder :: finished()
{
    if( !merge )
    {
        startIndex++;
        if( startIndex < files.size())
            start();
        else
            emit(allJobsDone());
    }
    else
        emit(allJobsDone());
}

void MEncoder :: readStandardOutput()
{
    // search for
    // Pos:  15.3s    458f (13%) 62.63fps Trem:   0min  37mb  A-V:0.058 [2484:223]

    QByteArray data = readAllStandardOutput();
    for( int i=0; i<data.size(); ++i )
    {
        switch( state )
        {
        case none:
            if( data.at(i) == 'P')
                state = p;
            else
                state = none;
            break;
        case p:
            if( data.at(i) == 'o')
                state = o;
            else
                state = none;
            break;
        case o:
            if( data.at(i) == 's')
                state = s;
            else
                state = none;
            break;
        case s:
            if( data.at(i) == ':')
            {
                state = colon;
                complete = "";
            }
            else
                state = none;
            break;
        case colon:
            if( data.at(i) == '(')
                state = open;
            break;
        case open:
            if( data.at(i) == '%')
            {
                state = none;
                int oldPercentage = percentage;
                percentage = complete.toInt();
                if( percentage != oldPercentage )
                {
                    complete = "";

                    if( percentage < oldPercentage )
                        file++;
                    emit( fileProgress(file,percentage));
                }
            }
            else
                complete += data.at(i);
            break;
        }
    }

    emit( textAvailable(QString(data)));
}
